package com.tanhua.server.service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.UserSound;
import com.tanhua.domain.mongo.UserSoundTime;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.PeachblossomApi;
import com.tanhua.server.exceptions.TanhuaException;
import com.tanhua.server.interceptors.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 桃花传音 服务
 *
 * @author 沈某
 * @date 2021/07/18 09:07:40
 */
@Service
public class PeachblossomService {

    @Reference
    private PeachblossomApi peachblossomApi;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Reference
    private UserInfoApi userInfoApi;

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    /**
     * @param soundFile 上传的音频文件
     * @return {@link ResponseEntity }
     * @throws IOException 流异常
     * @Author 沈某
     * @date 2021/07/17 11:07:48
     */
    public ResponseEntity savePeachblossom(MultipartFile soundFile) throws IOException {

        //获取音频的扩展名
        //获取文件名最后一个点后面的内容
        String fileName = soundFile.getName();
        String extname = fileName.substring(fileName.lastIndexOf(".") + 1);

        //
        StorePath storePath = storageClient.uploadFile(soundFile.getInputStream(), soundFile.getSize(), extname, null);
        String soundUrl = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();

        //创建对象保存数据
        UserSound userSound = new UserSound();
        userSound.setUserId(UserHolder.getUserId());
        userSound.setSoundUrl(soundUrl);
        peachblossomApi.save(userSound);

        return ResponseEntity.ok(null);
    }

    /**
     * @return {@link ResponseEntity }
     * @Author 沈某
     * @date 2021/07/17 11:07:03
     */
    public ResponseEntity queryPeachblossom() {

        Long userId = UserHolder.getUserId();
        //判断redis中有没有key
        Boolean hasKey = redisTemplate.hasKey("userSound_" + userId);
        //初始化访问次数
        Integer visitInt = 3;
        if (!hasKey){
            //不存在初始化一个新的key 并且把访问次数存入redis
            redisTemplate.boundValueOps("userSound_"+ userId).set(visitInt+"",1, TimeUnit.DAYS);
        }else {
            //存在就获取他的value
            String visit = redisTemplate.boundValueOps("userSound_"+ userId).get();
            if (visit!=null){
                visitInt = Integer.parseInt(visit);
                visitInt--;
                //每次访问后次数减一 然后存到redis中
                redisTemplate.boundValueOps("userSound_"+ userId).set(visitInt+"");
                if (visitInt<=0){
                    //要是没有访问次数直接抛出异常
                    throw new TanhuaException(500,"您的次数不够啦");
                }
            }
        }

        UserSound soundTime = peachblossomApi.queryPeachblossom(userId);//获取到一个随机的音频数据对象

        UserSoundTime userSoundTime = new UserSoundTime();//创建UserSoundTime对象 接收数据
        UserInfo userInfo = userInfoApi.findById(soundTime.getUserId());//通过获取到的音频对象
        BeanUtils.copyProperties(userInfo,userSoundTime);//调用工具方法组装数据
        userSoundTime.setId(Integer.parseInt(userInfo.getId().toString()));//这里是处理ID的类型转换
        userSoundTime.setSoundUrl(soundTime.getSoundUrl());
        String visit = redisTemplate.boundValueOps("userSound_" + userId).get();//再次获取存到redis中的value
        if (visit!=null){

            Integer remainingTimes1 = Integer.parseInt(visit);
            userSoundTime.setRemainingTimes(remainingTimes1);

            if (remainingTimes1>=1){
                peachblossomApi.delete(soundTime);//此时对获取到的音频 进行删除
            }
        }




        return ResponseEntity.ok(userSoundTime);
    }
}
